//
//  UILabel+Extension.m
//  测试 lable 自动拉伸
//
//  Created by 石虎 on 2017/5/3.
//  Copyright © 2017年 shihu. All rights reserved.
//

#import "UILabel+Extension.h"

@implementation UILabel (Extension)

+ (instancetype)createLabelWithFontOfSize:(CGFloat)fontSize andTextColor:(UIColor *)color{
    UILabel *lable = [[self alloc] init];
    lable.font = [UIFont systemFontOfSize:fontSize];
    lable.textColor = color;
    return lable;
}
/**
 自动适应 UILabel 的宽度
 
 @param content 文本内容
 @param view  添加 view
 @param fontSize 字体大小
 @param backgroundColor lable的背景颜色
 @param textColor 字体颜色
 @return 返回lable
 */
+ (instancetype)createLabelWithContent:(NSString *)content addView:(UIView *)view lableX:(CGFloat)lableX lableY:(CGFloat)lableY lableH:(CGFloat)lableH fontSize:(CGFloat)fontSize backgroundColor:(UIColor *)backgroundColor textColor:(UIColor *)textColor borderColor:(UIColor *)borderColor{
    
    NSString *string = [NSString stringWithFormat:@"%@",content];
    CGRect textRect = [self boundingString:string size:CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height *2) fontSize:fontSize];
    
    CGFloat rowWidth = 0.0;
    if (string.length == 1) {
        rowWidth = textRect.size.width + 35;
    }else{
        rowWidth = textRect.size.width + 25;
    }
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(lableX, lableY, rowWidth, lableH)];
    lable.layer.masksToBounds = YES;
    lable.layer.cornerRadius = 15;
    lable.layer.borderColor = borderColor.CGColor;
    lable.layer.borderWidth = 1;
    lable.backgroundColor = backgroundColor;
    lable.textAlignment = NSTextAlignmentCenter;
    lable.textColor = textColor;
    lable.text = string;
    [view addSubview:lable];
    
    return lable;
}
//自动适应 lable 的宽度 和 高度
+ (CGRect)boundingString:(NSString *)string size:(CGSize)size fontSize:(NSInteger)fontSize
{
    NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]};
    
    return [string boundingRectWithSize:size options:options attributes:attributes context:nil];
}
@end
